package com.fulihui.information.common.config;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import org.near.dal.sequence.SequenceKitLoader;
import org.near.database.api.SequenceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;

/**
 * @author Willard.Hu on 2016/11/26 0026.
 */
//@Configuration
//@PropertySource("file:conf/app.properties")
public class SpringConfig {
    @Autowired
    Environment env;
//    @Autowired
//    DataSourceService dataSourceService;

    @Bean
    public AppConst appConst() {
        AppConst appConst = new AppConst();
        appConst.setZbusUrl(env.getProperty("zbus.broker.address"));

        appConst.setOssKeyId(env.getProperty("aliyun.oss.accesskeyid"));
        appConst.setOssKeySeySecret(env.getProperty("aliyun.oss.accesskeysecret"));
        appConst.setOssEndpoint(env.getProperty("aliyun.oss.ossendpoint"));
        appConst.setOssBucket(env.getProperty("aliyun.oss.ossbucket"));

        appConst.setImgTmpDir(env.getProperty("image.tmp.dir"));

        return appConst;
    }

    /**
     * 序列化工具加载
     *
     * @param sequenceService 序列化配置服务
     * @return {@link SequenceKitLoader}
     */
    @Bean
    public SequenceKitLoader sequenceKitLoader(SequenceService sequenceService) {
        SequenceKitLoader sequenceKitLoader = new SequenceKitLoader();
        sequenceKitLoader.setServiceName("com.fulihui.information");
        sequenceKitLoader.setSequenceService(sequenceService);
        return sequenceKitLoader;
    }

    /**
     * Dubbo 的应用配置实例，默认名字使用主包名
     *
     * @return {@link ApplicationConfig}
     */
    @Bean
    public ApplicationConfig applicationConfig() {
        ApplicationConfig application = new ApplicationConfig();
        application
                .setName(env.getProperty("dubbo.application.name", "youkantou-data-gateway-proxy"));
        return application;
    }

    /**
     * Dubbo 注册中心配置实例，默认不使用注册中心
     *
     * @return {@link RegistryConfig}
     */
    @Bean
    public RegistryConfig registryConfig() {
        RegistryConfig registry = new RegistryConfig();
        registry.setProtocol(env.getProperty("dubbo.registry.protocol", ""));
        registry.setAddress(env.getProperty("dubbo.registry.address", "N/A"));
        return registry;
    }

    /**
     * <p>Dubbo 通讯协议设置实例</p>
     * <p>服务协议名称默认 dubbo</p>
     * <p>服务协议序列化方式默认 json</p>
     * <p>服务默认端口 20881</p>
     *
     * @return {@link ProtocolConfig}
     */
    @Bean
    public ProtocolConfig protocolConfig() {
        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.setName(env.getProperty("dubbo.protocol.name", "dubbo"));
        protocolConfig.setSerialization(env.getProperty("dubbo.protocol.serialization", "json"));
        protocolConfig.setPort(env.getProperty("dubbo.protocol.port", Integer.class, 20881));
        return protocolConfig;
    }

    /**
     * 配置log4j加载器，默认读取 resources 下的 log4j.xml
     *
     * @return {@link MethodInvokingFactoryBean}
     */
    @Bean
    public MethodInvokingFactoryBean log4jInitializer() {
        MethodInvokingFactoryBean factoryBean = new MethodInvokingFactoryBean();
        factoryBean.setStaticMethod("org.springframework.util.Log4jConfigurer.initLogging");
        factoryBean.setArguments(
                new Object[]{env.getProperty("fulihui.log4j.config.path", "file:conf/log4j.xml")});
        return factoryBean;
    }

    /**
     * Jedis 连接池配置类
     *
     * @return {@link JedisPoolConfig}
     */
    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(env.getProperty("redis.config.maxidle", Integer.class, 8));
        poolConfig.setMaxTotal(env.getProperty("redis.config.maxtotal", Integer.class, 8));
        return poolConfig;
    }

    /**
     * Jedis 连接池
     *
     * @param jedisPoolConfig {@link JedisPoolConfig}
     * @return {@link JedisPool}
     */
    @Bean
    public JedisPool jedisPool(JedisPoolConfig jedisPoolConfig) {
        return new JedisPool(jedisPoolConfig,
                env.getProperty("redis.pool.host", Protocol.DEFAULT_HOST),
                env.getProperty("redis.pool.port", Integer.class, Protocol.DEFAULT_PORT),
                env.getProperty("redis.pool.timeout", Integer.class, Protocol.DEFAULT_TIMEOUT),
                env.getProperty("redis.pool.password", (String) null));
    }

    /*
    <!-- 数据源配置 alibaba.druid 自动识别驱动类 -->
    <bean id="dataSource" class="org.near.dal.datasource.ExtDruidDatasource" init-method="init" destroy-method="close">
        <property name="dataSourceService" ref="dataSourceService"/>
	    <property name="dsCode" value="${datasouce.code}"/>
	    <property name="envType" value="${product.env}"/>

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="1"/>
        <property name="minIdle" value="1"/>
        <property name="maxActive" value="20"/>
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000"/>
        <!-- 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <!-- 配置一个连接在池中最小生存的时间，单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000"/>
        <property name="validationQuery" value="SELECT 'x'"/>
        <property name="testWhileIdle" value="true"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>
        <property name="poolPreparedStatements" value="false"/>
        <property name="maxPoolPreparedStatementPerConnectionSize" value="50"/>
        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat"/>
        <!-- 设置关闭自动提交 -->
        <property name="defaultAutoCommit" value="false"/>
    </bean>

    <!-- myBatis文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath*:META-INF/sqlmap/*-mapper.xml"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.fulihui.information.dal.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <!-- transaction support-->
    <!-- PlatformTransactionMnager -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
     */
//    @Bean
//    public ExtDruidDatasource extDruidDatasource() throws SQLException {
//        ExtDruidDatasource datasource = new ExtDruidDatasource();
//        datasource.setDataSourceService(dataSourceService);
//        datasource.setDsCode(env.getProperty("datasouce.code"));
//        datasource.setEnvType(env.getProperty("product.env"));
//        datasource.setInitialSize(1);
//        datasource.setMinIdle(1);
//        datasource.setMaxActive(20);
//        datasource.setMaxWait(60000);
//        datasource.setTimeBetweenEvictionRunsMillis(300000);
//        datasource.setValidationQuery("SELECT 'x'");
//        datasource.setTestWhileIdle(true);
//        datasource.setTestOnBorrow(false);
//        datasource.setTestOnReturn(false);
//        datasource.setPoolPreparedStatements(false);
//        datasource.setMaxPoolPreparedStatementPerConnectionSize(50);
//        datasource.setFilters("stat");
//        datasource.setDefaultAutoCommit(false);
//        return datasource;
//    }
//
//    @Bean
//    public SqlSessionFactoryBean sqlSessionFactory(ExtDruidDatasource datasource) {
//        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
//        factory.setDataSource(datasource);
//        factory.setMapperLocations(new Resource[]{new ClassPathResource("classpath*:META-INF/sqlmap/*-mapper.xml")});
//        return factory;
//    }
//
//    @Bean
//    public MapperScannerConfigurer mapperScannerConfigurer() {
//        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//        mapperScannerConfigurer.setBasePackage("com.fulihui.information.dal.mapper");
//        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
//        return mapperScannerConfigurer;
//    }
//
//    @Bean
//    public DataSourceTransactionManager dataSourceTransactionManager(ExtDruidDatasource datasource) {
//        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
//        dataSourceTransactionManager.setDataSource(datasource);
//        return dataSourceTransactionManager;
//    }
}